<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>简单登录</title>
</head>

<body>

    <body>
        <h1>用户登录</h1>

        <!-- 错误提示区域 -->
        <p id="error" style="color: red; display: none;"></p>

        <form id="from">
            <div>
                <span>用户名: </span>
                <input type="text" name="username">
            </div>
            <div>
                <span>密码: </span>
                <input type="password" name="password">
            </div>
            <button id="login" type="submit">登录</button>
            <button type="button" onclick="switchMethod()">切换提交方式 (当前: POST)</button>
        </form>

        <div id="success" style="display: none;">
            <h2>登录成功！</h2>
            <p id="welcomeMsg"></p>
            <button onclick="window.location.reload()">返回登录</button>
        </div>

        <script>
            // 提交方式标记（true为POST）
            let flag = true;

            // 切换提交方式
            function switchMethod() {
                flag = !flag;
                document.getElementById("login").textContent = `切换方式 (当前: ${flag ? 'POST' : 'GET'})`;
            }

            // 缓存元素
            const f = document.getElementById('from'),
                err = document.getElementById('error'),
                suc = document.getElementById('success'),
                msg = document.getElementById('welcomeMsg');

            // 表单提交
            f.addEventListener('submit', async (e) => {
                e.preventDefault(); //阻止元素默认行为
                const u = f.username.value.trim(), p = f.password.value.trim();

                if (!u || !p) return showError('请输入用户名和密码');

                try {
                    const d = `username=${encodeURIComponent(u)}&password=${encodeURIComponent(p)}`,
                        res = flag
                            ? await fetch('/submit', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: d })
                            : await fetch(`/submit?${d}`);

                    if (await res.text() === 'success') {
                        f.hidden = true;
                        suc.hidden = false;
                        msg.textContent = `欢迎，${u}！`;
                    } else showError('账号或密码错误（admin/123）');
                } catch {
                    showError('登录失败，请重试');
                }
            });

            // 错误提示
            function showError(m) {
                err.textContent = m;
                err.hidden = false;
                setTimeout(() => err.hidden = true, 3000);
            }
        </script>
    </body>

</html>

<!-- 以下是服务器代码，保存为同一文件，用Node.js运行 -->
<script type="text/javascript">
    // 仅在Node.js环境下运行服务器代码
    if (typeof require !== 'undefined') {
        const http = require('http');
        const fs = require('fs');
        const url = require('url');
        const querystring = require('querystring');
        const path = require('path');

        // 服务器配置
        const PORT = 3000;
        const validUser = { username: 'admin', password: '123' }; // 验证用户

        // 创建服务器
        const server = http.createServer((req, res) => {
            const parsedUrl = url.parse(req.url, true);

            // 处理登录请求
            if (parsedUrl.pathname === '/submit') {
                let data = {};

                // 处理GET请求
                if (req.method === 'GET') {
                    data = parsedUrl.query;
                }
                // 处理POST请求
                else if (req.method === 'POST') {
                    let body = '';
                    req.on('data', chunk => body += chunk);
                    req.on('end', () => {
                        data = querystring.parse(body);
                        validateAndRespond(data, res);
                    });
                    return;
                }

                validateAndRespond(data, res);
            }
            // 提供首页
            else {
                res.writeHead(200, { 'Content-Type': 'text/html' });
                // 读取当前文件作为HTML响应
                fs.readFile(path.basename(__filename), 'utf8', (err, content) => {
                    res.end(content);
                });
            }
        });

        // 验证用户并响应
        function validateAndRespond(data, res) {
            const isValid = data.username === validUser.username &&
                data.password === validUser.password;

            res.writeHead(200, { 'Content-Type': 'text/plain' });
            res.end(isValid ? 'success' : 'error');
        }

        // 启动服务器
        server.listen(PORT, () => {
            console.log(`服务器运行在 http://localhost:${PORT}`);
            console.log('测试账号: text / 123');
        });
    }
</script>